const express = require('express');
const router = express.Router();
// let db = require("../mysql/db")
const userInfo = require('../source/baseInfo');


/**
 * POST /api/v1/saveUser
 * @summary 添加用户
 * @description 添加用户
 * @tags [用户管理]
 * @produces application/json
 * @param {object} request.body.required - 用户信息
 * @return {object} 201 - 添加用户ok
 * @example request - 示例请求
 * {
 *    "name": "孙单单",
 *    "tel": 13240981227,
 *    "acount": "sundandan",
 *    "age": 18,
 *    "password": "sundandan110",
 *    "address": "河南省濮阳市郑州地区",
 *    "email": "sundandan110@qq.com"
 * }
 * @example response - 示例响应
 * {
 *   "data": 'ok'
 * }
 * @consumes application/json
 * @return {array<object>} 200 - 成功添加用户
 */
router.post('/api/v1/saveUser', async (req, res, next) => {
  const { id, name, age, tel,acount, password, email, address } = req.body;
  const fs = require('fs');
  const path = require('path'); //引入路径
  if(!(name&&age&& tel&&acount &&password&& email&&address)){
    res.json({ code: 202, data: [], message: '数据错误,参数有问题' });
  }else{
    let errortext=''
    try {
      const data = fs.readFileSync(path.join(__dirname, '../source/user.json'), 'utf8');
      // 解析JSON数据
      const jsonData = JSON.parse(data);

      const filterData = jsonData.filter((exp) => {
        return exp.acount === acount;
      });
      if(filterData.length>0){
        errortext = '已有该账号'
        res.json({ code: 201, data: {}, message: '已有该账号' });
      }else{
        const lastItem = jsonData.slice(-1)[0];
        const newdata = { id: (lastItem.id-0) + 1, name,acount, age, tel, password, email, address };
        try {
          const data1 = fs.writeFileSync(path.join(__dirname, '../source/user.json'), JSON.stringify([...jsonData,newdata]));
          console.log('已写入');
        } catch (error) {
          res.json({ code: 200, data: [], message: errortext?errortext:'数据获取成功' });
        }
      }
      
      
    } catch (err) {
      console.log(err)
      res.json({ code: 201, data: [], message: '数据错误,接口问题' });
    }
  }
 
  next();
});
/**
 * POST /api/v1/editUserById
 * @summary 编辑用户
 * @description 编辑用户
 * @tags [用户管理]
 * @produces application/json
 * @param {object} request.body.required - id
 * @return {object} 201 - 成功获取
 * @example request - 示例请求
 * {
 *    "id": 1,
 *    "name": "孙单单",
 *    "acount": "sundandan",
 *    "age": 18,
 *    "tel": 13240981227,
 *    "password": "sundandan110",
 *    "email": "sundandan110@qq.com",
 *    "address": "河南省濮阳市郑州地区"
 * }
 * @example response - 示例响应
 * {
 *  data: 'ok'
 * }
 * @return {object} 201 - 异常
 * @consumes application/json
 * @return {object} 200 - 成功获取教室
 */
router.post('/api/v1/editUserById', async (req, res, next) => {
  const { id, name, age, tel,acount, password, email, address } = req.body;
  const fs = require('fs');
  const path = require('path'); //引入路径
  try {
    const data = fs.readFileSync(path.join(__dirname, '../source/user.json'), 'utf8');
    // 解析JSON数据
    const jsonData = JSON.parse(data);
    const filterData = jsonData.filter((exp) => {
      return exp.id !== id;
    });

    let editData = jsonData.filter((exp) => {
      return exp.id === id;
    });
    if(filterData.length === jsonData.length-1 ){

      editData = [
        ...filterData,
        { id, name, age, tel,acount, password, email, address }
      ]

      try {
        const data1 = fs.writeFileSync(path.join(__dirname, '../source/user.json'), JSON.stringify(editData));
        console.log('已写入');
        res.json({ code: 200, data: 'ok', message: '数据编辑成功' });
      } catch (error) {
        res.json({ code: 201, data: 'error', message: '数据错误,接口问题' });
      }
    }else{
      res.json({ code: 201, data: 'error', message: 'id数据不存在' });
    }
   
   
  } catch (err) {
    res.json({ code: 201, data: 'error', message: '数据错误,接口问题' });
  }
  next();
});


/**
 * POST /api/v1/delUserById
 * @summary 删除用户
 * @description 删除用户
 * @tags [用户管理]
 * @produces application/json
 * @param {object} request.body.required - Userid
 * @return {object} 201 - 成功获取User
 * @example request - 示例请求
 * {
 *   "id": 1
 * }
 * @example response - 示例响应
 * {
 *  data: 'ok'
 * }
 * @return {object} 201 - 异常
 * @consumes application/json
 * @return {object} 200 - 成功获取用户
 */
router.post('/api/v1/delUserById', async (req, res, next) => {
  const { id } = req.body;
  const fs = require('fs');
  const path = require('path'); //引入路径
  try {
    const data = fs.readFileSync(path.join(__dirname, '../source/user.json'), 'utf8');
    // 解析JSON数据
    const jsonData = JSON.parse(data);
    const filterData = jsonData.filter((exp) => {
      return exp.id !== id;
    });
    try {
      const data1 = fs.writeFileSync(path.join(__dirname, '../source/user.json'), JSON.stringify(filterData));
      console.log('已写入');
      res.json({ code: 200, data: 'ok', message: '数据获取成功' });
    } catch (error) {
      res.json({ code: 201, data: 'error', message: '数据错误,接口问题' });
    }
  } catch (err) {
    res.json({ code: 201, data: 'error', message: '数据错误,接口问题' });
  }
  next();
});




/**
 * POST /api/v1/userLogin
 * @summary 登陆用户
 * @description 登陆用户
 * @tags [用户管理]
 * @produces application/json
 * @param {object} request.body.required - Userid
 * @return {object} 201 - 成功获取User
 * @example request - 示例请求
 * {
 *   "id": 1
 * }
 * @example response - 示例响应
 * {
 *  data: 'ok'
 * }
 * @return {object} 201 - 异常
 * @consumes application/json
 * @return {object} 200 - 成功获取用户
 */
router.post('/api/v1/userLogin', async (req, res, next) => {
  const { account,password } = req.body;
  const fs = require('fs');
  const path = require('path'); //引入路径
  try {
    const data = fs.readFileSync(path.join(__dirname, '../source/user.json'), 'utf8');
    // 解析JSON数据
    const jsonData = JSON.parse(data);
    const filterData = jsonData.filter((exp) => {
      return exp.account === account && exp.password === password;
    });
    if(filterData.length === 0){
      throw '用户名和密码错误'
    }
    res.json({ code: 200, data: filterData[0], message: '登录成功' });
  } catch (err) {
    res.json({ code: 201, data: 'error', message: '用户名和密码错误' });
  }
  next();
});


/**
 * POST /api/v1/getUserList
 * @summary 获取用户列表
 * @description 获取用户列表
 * @tags [用户管理]
 * @produces application/json
 * @example response - 示例响应
 * [
 *   {
 *    "id":1,
 *    "name": "孙单单",
 *    "tel": 13240981227,
 *    "acount": "sundandan",
 *    "age": 18,
 *    "password": "sundandan110",
 *    "address": "河南省濮阳市郑州地区",
 *    "email": "sundandan110@qq.com"
 *  },
 *  {
 *    "id": 2,
 *    "name": "孙00",
 *    "tel": 13240981221,
 *    "acount": "sundandan",
 *    "age": 18,
 *    "password": "sundandan110",
 *    "address": "河南省濮阳市郑州地区",
 *    "email": "sundandan110@qq.com"
 *  },
 * ]
 * @return {object} 201 - 异常
 * @consumes application/json
 * @return {object} 200 - 成功获取用户
 */
router.post('/api/v1/getUserList', async (req, res, next) => {
  const fs = require('fs');

  const path = require('path'); //引入路径
  try {
    const data = fs.readFileSync(path.join(__dirname, '../source/user.json'), 'utf8');
    // 解析JSON数据
    const jsonData = JSON.parse(data);
    res.json({ code: 200, data: jsonData, message: '数据获取成功' });
  } catch (err) {
    res.json({ code: 201, data: [], message: '数据错误,接口问题' });
  }
  next();
});




/**
 * POST /api/v1/getUserByPage
 * @summary 获取用户列表
 * @description 获取用户列表
 * @tags [用户管理]
 * @produces application/json
 * @param {object} request.body.required - Userid
 * @return {object} 201 - 成功获取User
 * @example request - 示例请求
 * {
 *   "name": "孙",
 *   "size":1
 * }
 * @example response - 200 - success response example
 * {
 *  "page":{
 *    "size":1,
 *    "count":21
 *  },
 *  "list":[
 *   {
 *    "id": 1,
 *    "name": "孙单单",
 *    "tel": 13240981227,
 *    "acount": "sundandan",
 *    "age": 18,
 *    "password": "sundandan110",
 *    "address": "河南省濮阳市郑州地区",
 *    "email": "sundandan110@qq.com"
 *  },
 *  {
 *    "id": 2,
 *    "name": "孙单单",
 *    "tel": 13240981227,
 *    "acount": "sundandan",
 *    "age": 18,
 *    "password": "sundandan110",
 *    "address": "河南省濮阳市郑州地区",
 *    "email": "sundandan110@qq.com"
 *  }
 * ]
 * }
 * @consumes application/json
 * @return {object} 200 - 成功获取用户
 */
router.post('/api/v1/getUserByPage', async (req, res, next) => {

  const { name,jxl,xq,jssbpz,rl,size } = req.body;

  const fs = require('fs');

  const path = require('path'); //引入路径
  let warningText= '';

  try {
    if(!(size)){
      warningText += '翻页参数size不能为空'
      throw '翻页数据不对'
    }
    const data = fs.readFileSync(path.join(__dirname, '../source/goods.json'), 'utf8');
    // 解析JSON数据
    const jsonData = JSON.parse(data);
    let filterData = jsonData

    if(name){
      filterData = filterData.filter((exp) => {
        return exp.name.includes(name);
      });
    }
   
    if(tel){
      filterData = filterData.filter((exp) => {
        return exp.tel.includes(tel);
      });
    }
    if(address){
      filterData = filterData.filter((exp) => {
        return exp.address.includes(address);
      });
    }

    if(email){
      filterData = filterData.filter((exp) => {
        return exp.email.includes(email);
      });
    }

    if(account){
      filterData = filterData.filter((exp) => {
        return exp.account.includes(account);
      });
    }
  
    res.json({ code: 200, data: {
      page:{
        size:size,
        count:filterData.length
      },
      list:filterData.slice(size*10-10,size*10)
    }, message: '数据获取成功' });
  } catch (err) {
    console.log(err)
    res.json({ code: 201, data: [], message: warningText?warningText:'数据错误,接口问题' });
  }
  next();
});


module.exports = router;
